class Song < ActiveRecord::Base
  has_many                    :blog_posts
  has_many                    :comments
  belongs_to                  :album
  has_many                    :shows,           :through => :set_lists
  has_many                    :videos
  has_many                    :set_lists
  has_attachment              :storage =>       :file_system,
                              :content_type =>  ['audio/mp3','audio/mpeg','audio/x-mpeg','audio/x-mp3','audio/mpeg3','audio/x-mpeg3','audio/x-mpegurl','audio/mpegurl', 'audio/mpg'],
                              :processor =>     :rmagick,
                              :max_size =>      50240.kilobytes
  validates_presence_of       :name
  
  before_save                 :assign_track
  
  before_destroy              :delete_comments
  
  has_friendly_id             :name,            :use_slug => true
  
  attr_accessible             :name, :lyrics, :purchase_link, :track,  #not sure why this needs to be here... suspect a problem with restful_authentication, but hey, it works. 8/25/2009
  
  def assign_track
    self.track ||= 0
  end
  
  def downloadable?
    self.filename.nil? ? (return false) : (return true)
  end
  
  def purchasable?
    self.purchase_link.nil? ? (return false) : (self.purchase_link.blank? ? (return false) : (return true))
  end
  
  def xml(song_url, home_url)
    xspf = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n"
    xspf << "<playlist version=\"0\" xmlns=\"http://xspf.org/ns/0/\">\n"
    xspf << "   <title>" + self.name + "</title>\n"
    xspf << "   <annotation>http://jettyrae.com</annotation>\n"
    xspf << "   <creator>Jetty Rae</creator>\n"
    xspf << "   <info>" + home_url + "</info>\n"
    xspf << "   <location>" + song_url + ".xml</location>\n"
    xspf << "   <license>http://creativecommons.org/licenses/by-sa/1.0/</license>\n"
    xspf << "   <trackList>\n"
    xspf << "\n"
    xspf << "     <track>\n"
    xspf << "       <location>" + self.public_filename + "</location>\n"
    xspf << "       <annotation>Jetty Rea - " + self.name + "</annotation>\n"
    xspf << "       <info>" + song_url + "</info>\n"
    xspf << "     </track>\n"
    xspf << "   </trackList>\n"
    xspf << "</playlist>"
    
    return xspf
  end

protected
  def delete_comments
    self.comments.each {|comment| comment.destroy}
  end
end
